# 将雨滴改为炸弹，并加入计时

import sys
import pygame
import random
import time
import threading
from pathlib import Path

import variable

# 初始化 Pygame
pygame.init()

# 设置屏幕大小
size = width, height = 800, 600
screen = pygame.display.set_mode(size)

# 设置颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
elapsed_time = 1


class MyThread(threading.Thread):
    def __init__(self):
        super().__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def run(self):
        while not self._stop_event.is_set():
            print("Thread is running...")
            time.sleep(1)
            global elapsed_time
            elapsed_time += 1
        print("Thread is stopping...")


# 加载图像并获取其 Rect
ball_image = pygame.image.load(
    f"{Path.cwd()}{variable.lufei}"
)  # 假设你有一个名为 'output.png' 的图像文件
ballrect = ball_image.get_rect(
    centerx=width // 2, centery=height - ball_image.get_height() // 2
)


def reset_game():
    global raindrops, ballrect, start_time, elapsed_time
    raindrops = [Raindrop() for _ in range(5)]
    ballrect = ball_image.get_rect(
        centerx=width // 2, centery=height - ball_image.get_height() // 2
    )
    start_time = time.time()
    elapsed_time = 0




def show_game_over(screen, t: MyThread):
    global game_state
    game_over_font = pygame.font.Font(None, 50)  # 使用默认字体和指定大小
    game_over_text = game_over_font.render("Game Over", True, (255, 0, 0))  # 红色文本
    game_over_rect = game_over_text.get_rect(
        center=(width // 2, height // 2 - 50)
    )  # 居中显示并调整位置

    button_font = pygame.font.Font(None, 30)  # 按钮字体
    restart_text = button_font.render("Restart", True, BLACK)
    restart_rect = restart_text.get_rect(
        center=(width // 2 - 80, height // 2 + 50)
    )  # 重启按钮位置
    quit_text = button_font.render("Quit", True, BLACK)
    quit_rect = quit_text.get_rect(center=(width // 2 + 80, height // 2 + 50))  # 退出按钮位置

    score_font = pygame.font.Font(None, 60)
    score_text = score_font.render(f"hold time: {elapsed_time} second !!", True, (255, 0, 0))
    score_rect = score_text.get_rect(center=(width // 2, height // 2 - 200))  # 退出按钮位置

    screen.fill(WHITE)  # 清空屏幕
    screen.blit(game_over_text, game_over_rect)  # 绘制文本到屏幕上
    screen.blit(restart_text, restart_rect)  # 绘制重启按钮
    screen.blit(quit_text, quit_rect)  # 绘制退出按钮
    screen.blit(score_text, score_rect)  # 绘制退出按钮
    pygame.display.flip()  # 更新屏幕显示

    # 等待用户点击按钮
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                t.stop()
                t.join()
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左键点击
                    if restart_rect.collidepoint(event.pos):
                        return
                    elif quit_rect.collidepoint(event.pos):
                        t.stop()
                        t.join()
                        pygame.quit()  # 退出 Pygame
                        sys.exit()  # 退出程序

    # 如果游戏结束循环结束，返回 None 或者根据需要进行其他操作
    return None


def draw_score(screen, elaspe_time, pos):
    font = pygame.font.Font(None, 36)  # 使用默认字体和指定大小
    text_surface = font.render(f"Time: {elaspe_time}", True, BLACK)  # 渲染文本到Surface对象
    text_rect = text_surface.get_rect(topright=pos)  # 将文本放在指定位置（右上角）
    screen.blit(text_surface, text_rect)  # 将文本绘制到屏幕上
    pygame.display.flip()  # 更新屏幕显示


# 创建一个线程并启动它


# 雨滴类
class Raindrop:
    def __init__(self):
        self.x = random.randint(0, width - 1)  # 随机x坐标
        self.y = 0 - random.randint(0, 30)  # 从屏幕顶部上方开始
        self.speed = random.randint(2, 5)  # 随机下落速度

    def move(self):
        self.y += self.speed

    def draw(self, screen):
        drop_img = pygame.image.load(
            f'{Path.cwd()}{variable.guided_missile}'
        ).convert_alpha()
        screen.blit(drop_img, (int(self.x), int(self.y)))

    def is_offscreen(self):
        return self.y > height


# 设置移动速度
speed = [5, 5]

# 雨滴列表
# raindrops = []  # 初始雨滴数量
raindrops = [Raindrop() for _ in range(5)]

start_time = time.time()
index = 0

# 游戏主循环
running = True
clock = pygame.time.Clock()  # 创建一个Clock对象来管理帧率
elapsed_time = 0
t = MyThread()
t.start()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            t.stop()
            t.join()
            sys.exit(1)

    # 使用 pygame.key.get_pressed() 来检测按键
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and ballrect.left > 0:
        ballrect.move_ip(-speed[0], 0)
    if keys[pygame.K_RIGHT] and ballrect.right < width:
        ballrect.move_ip(speed[0], 0)

    # 填充屏幕颜色
    screen.fill(WHITE)

    rain_mapping = {
        0: 5,
        1: 10,
        2: 15,
        3: 20,
        4: 25,
        5: 30,
    }

    now_time = time.time()
    elapse_time = round(now_time - start_time, 1)
    if elapse_time == 5.0:
        print(f"5-{index=}")
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 1])]

    if elapse_time == 10.0:
        print(f"10-{index=}")
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 2])]

    if elapse_time == 15.0:
        print(f"15-{index=}")
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 3])]

    if elapse_time == 20.0:
        print(f"20-{index=}")
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 3])]

    if elapse_time == 25.0:
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 4])]

    if elapse_time == 30.0:
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 5])]

    if elapse_time == 40.0:
        raindrops = [Raindrop() for _ in range(rain_mapping[index + 6])]

    # 绘制雨滴
    for drop in raindrops:
        drop.move()
        if not drop.is_offscreen():
            drop.draw(screen)
            # 检查雨滴是否与球相交
            if ballrect.colliderect(
                pygame.Rect(int(drop.x), int(drop.y), 1, 1)
            ):  # 假设雨滴用3x3的矩形表示
                show_game_over(screen, t)
                reset_game()

                break
        else:
            # 当雨滴移出屏幕时，重新生成一个新的雨滴
            raindrops.remove(drop)
            raindrops.append(Raindrop())

    # 绘制球
    screen.blit(ball_image, ballrect)

    # elaspe_time += 1
    # clock.tick(1)

    draw_score(screen, elapsed_time, (width - 10, 10))
    # 更新屏幕显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(60)

# 退出pygame
pygame.quit()
sys.exit()
